package com.core.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.UnsupportedEncodingException;

public class ClientHandler extends ChannelHandlerAdapter {



    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.buffer().writeBytes("你好,我是刘剑".getBytes()));
        // super.channelActive(ctx);
    }



    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String con = getMsg((ByteBuf) msg);
        System.out.println("客户端接收到的信息是：" + con);
        //super.channelRead(ctx, msg);
    }

    private String getMsg(ByteBuf buf) {
        byte[] b = new byte[buf.readableBytes()];
        buf.readBytes(b);

        try {
            return new String(b, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }
}
